<template>
  <div class="mb-5">
    <div class="flex items-center mb-3">
      <img :src="sun" alt="sun" class="w-6 h-6 mr-2" />
      <h3 class="text-lg font-medium">Solar</h3>
    </div>
    <div class="grid grid-cols-5 gap-3">
      <!-- 太阳能发电折线图 -->
      <div class="solar-line-chart col-span-3 chart-box">
        <h4 class="text-base font-medium">Solar Power Generation</h4>
        <div class="text-2xl font-bold mt-1 mb-3">{{ totalPower }} kWh</div>
        <div class="text-sm text-gray-500 mb-2">Solar Power (kWh)</div>
        <div ref="lineChartRef" class="chart-container" style="height: 250px"></div>
      </div>

      <!-- 能源去向饼图 -->
      <div class="energy-pie-chart col-span-2 chart-box">
        <h4 class="text-base font-medium">Energy Destination</h4>
        <div class="mt-4">
          <div ref="pieChartRef" class="chart-container" style="height: 250px"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, markRaw, nextTick, computed, watch } from "vue";
import { getMockData, calculateTotals, calculatePieData } from "./mock";
import * as echarts from "echarts/core";
import { TitleComponent, TooltipComponent, LegendComponent } from "echarts/components";
import { LineChart, PieChart, BarChart } from "echarts/charts";
import { CanvasRenderer } from "echarts/renderers";
import sun from "./assets/sun.png";

// 组件props
interface Props {
  timeScope?: "day" | "week" | "month" | "year";
  dataType?: "data" | "analysis";
  timeType: number;
  processedData?: any;
  energyTotals?: any;
  isLoading?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  timeScope: "day",
  dataType: "data",
  timeType: 0,
  isLoading: false
});
// 注册 ECharts 组件
echarts.use([TitleComponent, TooltipComponent, LegendComponent, LineChart, PieChart, BarChart, CanvasRenderer]);

const lineChartRef = ref(null);
const pieChartRef = ref(null);

// 移除hook使用，改为接收父组件数据
// const { isLoading, isNothing, energyTotals, processedData, getSolarFlowData } = useEnergyData();

// 计算属性 - 获取当前数据（保持兼容性）
const currentData = computed(() => {
  return getMockData(props.timeScope, props.dataType);
});

// 计算属性 - 汇总数据
const summaryData = computed(() => {
  return calculateTotals(currentData.value.energyData);
});

// 计算属性 - 饼状图数据
const pieData = computed(() => {
  return calculatePieData(currentData.value.energyData);
});

// 计算属性 - 图表类型
const chartType = computed(() => {
  return props.timeScope === "day" ? "line" : "bar";
});

// 计算属性 - 总功率
const totalPower = computed(() => {
  if (props.dataType === "data" && props.energyTotals) {
    return (props.energyTotals.solarTotal / 1000).toFixed(2);
  }
  const totals = calculateTotals(currentData.value.energyData);
  return (totals.totalBattery + totals.totalGrid + totals.totalHome).toFixed(2);
});
// 图表实例
let lineChart: any = null;
let pieChart: any = null;

// 创建主图表配置
const createMainChartOption = () => {
  const isLine = chartType.value === "line";
  const isAnalysis = props.dataType === "analysis";

  // 颜色配置 - 与饼图保持一致
  const colors = {
    battery: "#3498db", // 蓝色
    grid: "#9ca3af", // 灰色
    home: "#10b981" // 绿色
  };

  // 根据dataType选择数据源
  let chartData: any;
  let timePoints: string[];

  if (props.dataType === "data" && props.processedData) {
    // 使用真实数据
    chartData = props.processedData.solarList;
    timePoints = props.processedData.timePoints;
    console.log("SolarCard 使用真实数据:", {
      chartData: chartData?.slice(0, 5),
      timePoints: timePoints?.slice(0, 5),
      dataLength: chartData?.length
    });
  } else {
    // 使用mock数据
    const mockData = currentData.value;
    chartData = mockData.energyData;
    timePoints = mockData.timePoints;
    console.log("SolarCard 使用mock数据:", {
      chartData: chartData?.slice(0, 5),
      timePoints: timePoints?.slice(0, 5)
    });
  }

  return {
    grid: {
      left: "3%",
      right: "4%",
      bottom: isAnalysis ? "15%" : "10%",
      top: "5%",
      containLabel: true
    },
    tooltip: {
      trigger: "axis",
      formatter: (params: any) => {
        if (isAnalysis) {
          // Analysis模式下的详细提示
          const point = params[0];
          const energyPoint = currentData.value.energyData[point.dataIndex];
          return `
            <div><strong>${point.name}</strong></div>
            <div style="color: ${colors.battery}">● Battery: ${energyPoint.battery} kWh</div>
            <div style="color: ${colors.grid}">● Grid: ${energyPoint.grid} kWh</div>
            <div style="color: ${colors.home}">● Home: ${energyPoint.home} kWh</div>
          `;
        } else {
          // Data模式下的简单提示
          const point = params[0];
          return `
            <div><strong>${point.name}</strong></div>
            <div>Solar Power: ${point.value} W</div>
          `;
        }
      }
    },
    legend: isAnalysis
      ? {
          data: [
            {
              name: "Battery",
              icon: "circle",
              textStyle: { color: colors.battery }
            },
            {
              name: "Grid",
              icon: "circle",
              textStyle: { color: colors.grid }
            },
            {
              name: "Home",
              icon: "circle",
              textStyle: { color: colors.home }
            }
          ],
          bottom: 5,
          left: "center",
          itemGap: 20,
          textStyle: {
            color: "#666",
            fontSize: 12
          }
        }
      : undefined,
    xAxis: {
      type: "category",
      data: timePoints,
      axisLabel: {
        color: "#333"
      },
      axisLine: {
        lineStyle: {
          color: "#E0E0E0"
        }
      }
    },
    yAxis: {
      type: "value",
      axisLine: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: "#F5F5F5"
        }
      }
    },
    series: isAnalysis
      ? [
          // Analysis模式：分别显示三个系列
          {
            name: "Battery",
            data: currentData.value.energyData.map((point: any) => point.battery),
            type: isLine ? "line" : "bar",
            smooth: isLine,
            stack: isLine ? undefined : "total",
            lineStyle: isLine
              ? {
                  color: colors.battery,
                  width: 3
                }
              : undefined,
            itemStyle: {
              color: colors.battery
            },
            symbol: isLine ? "circle" : undefined,
            symbolSize: isLine ? 6 : undefined,
            areaStyle: isLine
              ? {
                  color: {
                    type: "linear",
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [
                      {
                        offset: 0,
                        color: colors.battery + "40"
                      },
                      {
                        offset: 1,
                        color: colors.battery + "05"
                      }
                    ]
                  }
                }
              : undefined
          },
          {
            name: "Grid",
            data: currentData.value.energyData.map((point: any) => point.grid),
            type: isLine ? "line" : "bar",
            smooth: isLine,
            stack: isLine ? undefined : "total",
            lineStyle: isLine
              ? {
                  color: colors.grid,
                  width: 3
                }
              : undefined,
            itemStyle: {
              color: colors.grid
            },
            symbol: isLine ? "circle" : undefined,
            symbolSize: isLine ? 6 : undefined,
            areaStyle: isLine
              ? {
                  color: {
                    type: "linear",
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [
                      {
                        offset: 0,
                        color: colors.grid + "40"
                      },
                      {
                        offset: 1,
                        color: colors.grid + "05"
                      }
                    ]
                  }
                }
              : undefined
          },
          {
            name: "Home",
            data: currentData.value.energyData.map((point: any) => point.home),
            type: isLine ? "line" : "bar",
            smooth: isLine,
            stack: isLine ? undefined : "total",
            lineStyle: isLine
              ? {
                  color: colors.home,
                  width: 3
                }
              : undefined,
            itemStyle: {
              color: colors.home
            },
            symbol: isLine ? "circle" : undefined,
            symbolSize: isLine ? 6 : undefined,
            areaStyle: isLine
              ? {
                  color: {
                    type: "linear",
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [
                      {
                        offset: 0,
                        color: colors.home + "40"
                      },
                      {
                        offset: 1,
                        color: colors.home + "05"
                      }
                    ]
                  }
                }
              : undefined
          }
        ]
      : [
          // Data模式：显示总计
          {
            name: "Solar Power",
            data: chartData,
            type: isLine ? "line" : "bar",
            smooth: isLine,
            lineStyle: isLine
              ? {
                  color: "#fcc419",
                  width: 3
                }
              : undefined,
            itemStyle: {
              color: "#fcc419"
            },
            symbol: isLine ? "none" : undefined,
            areaStyle: isLine
              ? {
                  color: {
                    type: "linear",
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [
                      {
                        offset: 0,
                        color: "rgba(252, 196, 25, 0.2)"
                      },
                      {
                        offset: 1,
                        color: "rgba(252, 196, 25, 0.01)"
                      }
                    ]
                  }
                }
              : undefined
          }
        ]
  };
};

// 创建饼图配置
const createPieChartOption = () => {
  return {
    tooltip: {
      trigger: "item",
      formatter: "{b}: {c} kWh ({d}%)"
    },
    series: [
      {
        name: "Energy Destination",
        type: "pie",
        radius: ["40%", "70%"],
        center: ["50%", "50%"],
        avoidLabelOverlap: false,
        padAngle: 8,
        itemStyle: {
          borderColor: "#fff",
          borderWidth: 3,
          borderRadius: 8
        },
        label: {
          show: true,
          position: "outside",
          formatter: function (params: any) {
            return `{name|${params.name}}\n{value|${params.value} kWh}\n{percent|${params.percent}%}`;
          },
          rich: {
            name: {
              fontSize: 12,
              color: "#333",
              fontWeight: "bold"
            },
            value: {
              fontSize: 11,
              color: "#666",
              lineHeight: 16
            },
            percent: {
              fontSize: 11,
              color: "#999",
              lineHeight: 16
            }
          }
        },
        labelLine: {
          show: true,
          length: 10,
          length2: 20,
          lineStyle: {
            color: "#999"
          }
        },
        emphasis: {
          scale: true,
          scaleSize: 5,
          itemStyle: {
            borderColor: "#fff",
            borderWidth: 3,
            borderRadius: 8,
            shadowBlur: 15,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.3)"
          }
        },
        data: pieData.value.map((item) => ({
          value: item.value,
          name: item.name,
          itemStyle: {
            color: item.color,
            borderColor: "#fff",
            borderWidth: 3,
            borderRadius: 8
          }
        }))
      }
    ]
  };
};

// 初始化图表
const initCharts = () => {
  nextTick(() => {
    // 初始化主图表
    if (lineChartRef.value) {
      lineChart = markRaw(echarts.init(lineChartRef.value));
      lineChart.setOption(createMainChartOption());

      window.addEventListener("resize", () => {
        lineChart?.resize();
      });
    }

    // 初始化饼图
    if (pieChartRef.value) {
      pieChart = markRaw(echarts.init(pieChartRef.value));
      pieChart.setOption(createPieChartOption());

      window.addEventListener("resize", () => {
        pieChart?.resize();
      });
    }
  });
};

// 更新图表
const updateCharts = () => {
  // 直接更新图表，数据由父组件提供
  if (lineChart) {
    lineChart.setOption(createMainChartOption(), true);
  }
  if (pieChart) {
    pieChart.setOption(createPieChartOption(), true);
  }
};

// 监听props变化，更新图表
watch(
  [() => props.processedData, () => props.energyTotals, () => props.dataType],
  () => {
    console.log("SolarCard 监听到props变化:", {
      hasProcessedData: !!props.processedData,
      solarListLength: props.processedData?.solarList?.length,
      dataType: props.dataType,
      hasEnergyTotals: !!props.energyTotals
    });

    if (props.processedData && props.processedData.solarList) {
      nextTick(() => {
        console.log("SolarCard 开始更新图表");
        updateCharts();
      });
    }
  },
  { deep: true, immediate: true }
);

defineExpose({
  updateCharts
});

onMounted(() => {
  initCharts();
});
</script>

<style scoped>
.chart-container {
  width: 100%;
}

.chart-box {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 16px;
  background: #fff;
}
</style>
